package com.kzd.gtgame.main.mine

import android.os.Bundle
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.setTransitionStatusE
import com.kzd.gtgame.jetpack.vm.MineViewModel
import com.kzd.gtgame.main.mine.adapter.MineRecordBillAdapter
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.include_app_refresh.*

class MineRecordBillFragment : OwnerViewModeFragment<MineViewModel>() {

    companion object {
        const val KEY_COLLECT_ACTION = "KEY_COLLECT_ACTION"
        fun newInstance(action: Int): MineRecordBillFragment {
            val bundle = Bundle().apply {
                putInt(KEY_COLLECT_ACTION, action)
            }
            return MineRecordBillFragment().apply {
                arguments = bundle
            }
        }
    }

    private val mMineRecordBillAdapter = MineRecordBillAdapter()

    private val mAction: Int by lazy {
        arguments?.getInt(KEY_COLLECT_ACTION) ?: 0
    }

    override fun viewModel(): MineViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.include_app_refresh

    override fun initView() {

        rvAppRefreshBody.apply {
            layoutManager = LinearLayoutManager(context)
        }.adapter = mMineRecordBillAdapter

        mSmartRefreshLayout.setOnRefreshListener {
            viewModel.mineMyOrder(mAction)
        }
        mSmartRefreshLayout.setOnLoadMoreListener {
            viewModel.mineMyOrder(mAction, isLoadMore = true)
        }
    }

    override fun initData() {
        viewModel.mineMyOrder(mAction)
    }

    override fun initViewMode() {
        viewModel.mineOrderLiveData.observe(this as LifecycleOwner, { response ->
            setTransitionStatusE(response, mMineRecordBillAdapter, mSmartRefreshLayout)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            val isLoadMore = response.data?.isLoadMore
                ?: return@observe
            if (isLoadMore) {
                mMineRecordBillAdapter.addData(data)
            } else {
                mMineRecordBillAdapter.setNewInstance(data)
            }
        })
    }

}